package com.starbucks.opencase.function;

import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 口令处理
 */
@Component
public class funCommand {
    private char[] ks={
            '0','1','2','3','4','5','6','7','8','9',
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
    };
    /**
     * 创建口令
     * @param uid
     * @return
     */
    public String create(String uid){
        String qw=uid+","+(System.currentTimeMillis()+1000*60*60*24*7);
        qw=Base64.getEncoder().encodeToString(qw.getBytes(StandardCharsets.UTF_8));
        char[] verity=countVerity(qw);
        if(verity.length!=4)return "";
        return ""+verity[0]+verity[1]+verity[2]+verity[3]+qw;
    }

    /**
     * 解密口令
     * @param command {phone,end_time}
     * @return
     */
    public String[] decode(String command){
        String a=command.substring(4);
        char[] verity=countVerity(a);
        if(verity.length!=4)return null;
        if(verity[0]!=command.charAt(0) || verity[1]!=command.charAt(1) || verity[2]!=command.charAt(2) || verity[3]!=command.charAt(3))return null;
        return new String(Base64.getDecoder().decode(a),StandardCharsets.UTF_8).split(",");
    }

    /**
     * 获取校验码
     * @param command
     * @return
     */
    private char[] countVerity(String command){
        int a=0,b=0,c=0,d=0;
        for(int i=0;i<command.length();i++){
            if(i%2==0)a+=command.charAt(i);
            else b+=command.charAt(i);
            if(i%3==0 || i%7==0)c+=command.charAt(i);
            d+=command.charAt(i);
            a%=ks.length;
            b%=ks.length;
            c%=ks.length;
            d%=ks.length;
        }
        return new char[]{ks[a],ks[b],ks[c],ks[d]};
    }
}
